//
//  NEDNotificationHUB.m
//  SuoShi
//
//  Created by 林宁宁 on 2019/10/31.
//  Copyright © 2019 小红许. All rights reserved.
//

#import "NEDNotificationHUB.h"
#import <YYCategories/UIGestureRecognizer+YYAdd.h>
#import <YYCategories/NSTimer+YYAdd.h>
#import <Masonry/Masonry.h>
#import <NEDApp/NEDDeviceInfo.h>
#import <NEDConstant/NEDConstant.h>

#define kNEDNotificationHUBSpace 6

@interface NEDNotificationHUB ()

@property (retain, nonatomic) NSTimer * timerAfter;

@end

@implementation NEDNotificationHUB

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        [self ned_commonInit];
    }
    return self;
}
-(void)ned_commonInit{
         
    self.duration = 4;
    
    self.contentView = [UIView new];
    self.contentView.clipsToBounds = YES;
    self.contentView.layer.cornerRadius = 10;
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake([NEDDeviceInfo height_bar_status], kNEDNotificationHUBSpace, kNEDNotificationHUBSpace, kNEDNotificationHUBSpace));
    }];
    
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.backgroundColor = [UIColor whiteColor];
    
    [self.contentView addSubview:effectView];
    [effectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
    
    self.imageView = [UIImageView new];
    self.imageView.userInteractionEnabled = NO;
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.layer.cornerRadius = 4.0f;
    self.imageView.clipsToBounds = YES;
    [self.contentView addSubview:self.imageView];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.contentView);
        make.size.mas_equalTo(CGSizeMake(30, 30));
        make.left.equalTo(self.contentView).offset(kNEDNotificationHUBSpace);
    }];
    
    self.textLabel = [UILabel new];
    self.textLabel.font = [UIFont systemFontOfSize:15];
    self.textLabel.textColor = [UIColor darkTextColor];
    self.textLabel.numberOfLines = 1;
    self.textLabel.textAlignment = NSTextAlignmentLeft;
    self.textLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.textLabel.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.textLabel];
    [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView);
        make.left.equalTo(self.imageView.mas_right).offset(kNEDNotificationHUBSpace);
        make.right.equalTo(self.contentView).offset(-kNEDNotificationHUBSpace);
    }];

    self.detailTextLabel = [UILabel new];
    self.detailTextLabel.font = [UIFont systemFontOfSize:13];
    self.detailTextLabel.textColor = [UIColor lightTextColor];
    self.detailTextLabel.numberOfLines = 1;
    self.detailTextLabel.textAlignment = NSTextAlignmentLeft;
    self.detailTextLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.detailTextLabel.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.detailTextLabel];
    [self.detailTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textLabel.mas_bottom);
        make.left.equalTo(self.textLabel);
        make.right.equalTo(self.contentView).offset(-kNEDNotificationHUBSpace);
        make.bottom.equalTo(self.contentView);
        make.height.mas_equalTo(0);
    }];
    
    
    WS(weakSelf);
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        if(weakSelf.tapActionBlock){
            weakSelf.tapActionBlock(weakSelf);
        }
        [weakSelf dismiss];
    }];
    [self addGestureRecognizer:tap];
    
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf panEvent:sender];
    }];
    [self addGestureRecognizer:pan];
    
    self.backgroundColor = [UIColor clearColor];
    self.contentView.backgroundColor = [UIColor clearColor];
    self.imageView.backgroundColor = [UIColor clearColor];
    self.textLabel.backgroundColor = [UIColor clearColor];
    self.detailTextLabel.backgroundColor = [UIColor clearColor];
    
//    self.backgroundColor = [UIColor redColor];
//    self.contentView.backgroundColor = [UIColor orangeColor];
//    self.imageView.backgroundColor = [UIColor blueColor];
//    self.textLabel.backgroundColor = [UIColor yellowColor];
//    self.detailTextLabel.backgroundColor = [UIColor greenColor];
    
}

- (void)show{
    [NEDNotificationHUB dismiss];
//    [self.contentView cornerAll:6];
    UIView * superV = [UIApplication sharedApplication].delegate.window;
    [superV addSubview:self];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(superV);
        make.height.mas_equalTo([NEDDeviceInfo height_bar_navigation]+26);
    }];
    
    self.transform = CGAffineTransformMakeTranslation(0, -[NEDDeviceInfo height_bar_navigation]);
    [UIView animateWithDuration:0.2 delay:0 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
        
        self.transform = CGAffineTransformIdentity;
        
    } completion:^(BOOL finished) {
        
        [self timerAfterBegin];
    }];
}

- (void)panEvent:(UIPanGestureRecognizer *)sender{
    if(sender.state == UIGestureRecognizerStateChanged ||
       sender.state == UIGestureRecognizerStateEnded){
        
        CGPoint offset = [sender translationInView:self];
//        NSLog(@"%@",NSStringFromCGPoint(offset));
        
        if(sender.state == UIGestureRecognizerStateChanged){
            [self timerAfterStop];
            
            if(offset.y < 0){
                self.transform = CGAffineTransformMakeTranslation(0, offset.y);
            }
        }else{
            
            if(ABS(offset.y) > CGRectGetHeight(self.contentView.frame)*0.5){
                // 超过一半 要自动移出去
                [UIView animateWithDuration:0.2 animations:^{
                    self.transform = CGAffineTransformMakeTranslation(0, -CGRectGetHeight(self.frame));
                } completion:^(BOOL finished) {
                    [self dismiss];
                }];
            }else{
                //恢复 过段时间再消失
                [UIView animateWithDuration:0.2 animations:^{
                    self.transform = CGAffineTransformIdentity;
                } completion:^(BOOL finished) {
                    [self timerAfterBegin];
                }];
            }
        }
    }
}

- (void)timerAfterBegin{
    [self timerAfterStop];
    if(!self.superview){
        return;
    }
    WS(weakSelf);
    self.timerAfter = [NSTimer scheduledTimerWithTimeInterval:self.duration block:^(NSTimer * _Nonnull timer) {
        [weakSelf dismiss];
    } repeats:NO];
//    [self.timerAfter fire];
}

- (void)timerAfterStop{
    if(self.timerAfter){
        [self.timerAfter invalidate];
        self.timerAfter = nil;
    }
}

- (void)dismiss{
    [self timerAfterStop];
    if(self.superview){
        [UIView animateWithDuration:0.2 delay:0 options:(UIViewAnimationOptionCurveLinear) animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }
//    else{
//        NSLog(@"已移除");
//    }
}


-(void)layoutSubviews{
    [super layoutSubviews];
    NSString * detailText = self.detailTextLabel.text;
    if(IsNonNull(detailText)){
        //字标题非空
        self.textLabel.numberOfLines = 1;
        self.detailTextLabel.numberOfLines = 1;
        [self.detailTextLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(self.detailTextLabel.font.lineHeight+12);
            make.top.equalTo(self.textLabel.mas_bottom).offset(-8);
        }];
    }else{
        self.textLabel.numberOfLines = 2;
    }
    if(self.imageView.image){
        [self.textLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.imageView.mas_right).offset(kNEDNotificationHUBSpace);
        }];
    }else{
        [self.textLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(kNEDNotificationHUBSpace*2);
        }];
    }
    
//    [self.contentView ned_addShadow:^(CALayer *shadowLayer) {
//
//    }];
}

+ (NEDNotificationHUB *)showText:(NSString *)text{
    return [NEDNotificationHUB showConfig:^(NEDNotificationHUB * _Nonnull passHUB) {
        passHUB.textLabel.text = text;
    }];
}

+ (NEDNotificationHUB *)showConfig:(void(^_Nullable)(NEDNotificationHUB * passHUB))configBlock{
    [NEDNotificationHUB dismiss];
    
    NEDNotificationHUB * hub = [NEDNotificationHUB new];
    if(configBlock){
        configBlock(hub);
    }
    
    [hub show];
    
    return hub;
}



+ (void)dismiss{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    for(NEDNotificationHUB * subV in window.subviews){
        if([subV isKindOfClass:[NEDNotificationHUB class]]){
            [subV dismiss];
        }
    }
}

@end

